package com.ruoyi.utils;
import com.alibaba.fastjson2.JSON;
import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.CreateJsapiTicketResponse;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Description
 * @Author zeo
 * @Date 2024/8/22 15:38
 */
public class DingTalkUtils {

    private static String corpId = "dingdd68e5ace8321d7a35c2f4657eb6378f";

    private static String agentId = "3331951856";

    private static String appKey = "dingqncbmzxywi7z7aht";

    private static String appSecret = "0SN1QZp8ywjp-qUIAo_vqyDZhQE85POzsyIZGedjIxMue0mI0VJuW8sXbAX2anBV";

    public static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }

    public static String getAccessToken() throws Exception {
        Client client = DingTalkUtils.createClient();
        GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest()
                .setAppKey(appKey)
                .setAppSecret(appSecret);
        try {
            GetAccessTokenResponse response = client.getAccessToken(getAccessTokenRequest);
            String accessToken = response.getBody().getAccessToken();
            return accessToken;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getJsapiTicket(String token) throws Exception {
        com.aliyun.dingtalkoauth2_1_0.Client client = createClient();
        com.aliyun.dingtalkoauth2_1_0.models.CreateJsapiTicketHeaders createJsapiTicketHeaders = new com.aliyun.dingtalkoauth2_1_0.models.CreateJsapiTicketHeaders();
        createJsapiTicketHeaders.xAcsDingtalkAccessToken = token;
        try {
            CreateJsapiTicketResponse jsapiTicketWithOptions = client.createJsapiTicketWithOptions(createJsapiTicketHeaders, new RuntimeOptions());
            String jsapiTicket = jsapiTicketWithOptions.getBody().getJsapiTicket();
            return jsapiTicket;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //import com.dingtalk.oapi.lib.aes.DingTalkJsApiSingnature;
    public static Map getSign(String jsticket, String url) throws Exception {
        url = URLDecoder.decode(url, "UTF-8");

        long timestamp = System.currentTimeMillis();
        String nonceStr = getNonceStr();
        String plain = "jsapi_ticket=" + jsticket + "&noncestr=" + nonceStr + "&timestamp=" + String.valueOf(timestamp)
                + "&url=" + url;
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-256");
            sha1.reset();
            sha1.update(plain.getBytes("UTF-8"));
            String sign = byteToHex(sha1.digest());

            Map map = new HashMap<>();
            map.put("agentId", agentId);
            map.put("corpId", corpId);
            map.put("timeStamp", timestamp);
            map.put("nonceStr", nonceStr);
            map.put("signature", sign);
            String[] jsApiList = new String[]{"complexChoose", "chooseStaffForPC", "choose", "biz.contact.choose", "chooseDepartments"};
            map.put("jsApiList", jsApiList);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据手机号查询用户信息
     *
     * @param accessToken
     * @param mobile
     */
    public static void getUserByMobile(String accessToken, String mobile) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(mobile);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param accessToken token
     */
    public static void sendMessageSQD(String accessToken, String id, String fqr, String xmmc, String xzrq, String jxmc, String fqsj, String userIds, String singleTitle, String url) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(Long.parseLong(agentId));
            request.setUseridList(userIds);
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setActionCard(new OapiMessageCorpconversationAsyncsendV2Request.ActionCard());

            msg.setMsgtype("action_card");

            msg.getActionCard().setTitle(fqr + "发起的机械使用申请表");
            msg.getActionCard().setMarkdown("**" + fqr + "发起的机械使用申请表**  \n  项目名称：" + xmmc + "  \n  日期：" + xzrq + "  \n  机械名称：" + jxmc + "  \n  发起人：" + fqr + "  \n  发起时间：" + fqsj);

            msg.getActionCard().setSingleTitle(singleTitle);

            // 发送type为审批确认单以及insert的id,前端路由获取到type以及id,跳转到审批页点击同意审批
            msg.getActionCard().setSingleUrl(url + id);

            request.setMsg(msg);
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, accessToken);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendMessage(String accessToken, String userIds) {
        try {
            UUID uuid = UUID.randomUUID();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(Long.parseLong(agentId));
            request.setUseridList(userIds);
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setActionCard(new OapiMessageCorpconversationAsyncsendV2Request.ActionCard());

            msg.setMsgtype("action_card");

            msg.getActionCard().setTitle("setTitle");
            msg.getActionCard().setMarkdown("宝尚token已过期" + uuid.toString());

            msg.getActionCard().setSingleTitle("点击获取验证码");
            msg.getActionCard().setSingleUrl("http://47.96.100.131:8082/");
            request.setMsg(msg);
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, accessToken);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Map getUserInfo(String accessToken, String code) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            req.setCode(code);
            OapiV2UserGetuserinfoResponse rsp = client.execute(req, accessToken);
            return JSON.parseObject(rsp.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDepartmentListSub(String accessToken, Long deptId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
            req.setDeptId(deptId);
            req.setLanguage("zh_CN");
            OapiV2DepartmentListsubResponse rsp = client.execute(req, accessToken);
            return rsp.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDepartmentListSubId(String accessToken, Long deptId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsubid");
            OapiV2DepartmentListsubidRequest req = new OapiV2DepartmentListsubidRequest();
            req.setDeptId(deptId);
            OapiV2DepartmentListsubidResponse rsp = client.execute(req, accessToken);
            return rsp.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDepartmentGet(String accessToken, Long deptId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsubid");
            OapiV2DepartmentListsubidRequest req = new OapiV2DepartmentListsubidRequest();
            req.setDeptId(deptId);
            OapiV2DepartmentListsubidResponse rsp = client.execute(req, accessToken);
            return rsp.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getUserList(String accessToken, Long deptId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
            OapiV2UserListRequest req = new OapiV2UserListRequest();
            req.setDeptId(deptId);
            req.setCursor(0L);
            req.setSize(30L);
            req.setLanguage("zh_CN");
            OapiV2UserListResponse rsp = client.execute(req, accessToken);
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }


    // 字节数组转化成十六进制字符串
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static String getNonceStr() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static void main(String[] args) {
        try {
            String accessToken = getAccessToken();
            sendMessage(accessToken,"21501764271176528");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
